from django.contrib.auth.backends import ModelBackend
from django.db.models import Q

from users.models import User


def jwt_response_payload_handler(token, user=None, request=None):
    """
    自定义jwt认证成功返回数据
    """
    return {
        'token': token,
        'user_id': user.id,
        'username': user.username
    }

#ModelBackend: django默认登录校验的后台(管理类)
class UsernameMobileAuthBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        """
        判断用户名/手机号 和密码是否正确
        :param request:
        :param username:
        :param password:
        :param kwargs:
        :return:
        """
        #查询用户

        query_set = User.objects.filter(Q(username=username)|Q(mobile=username))
        try:
            if query_set.exists():
                user = query_set.get()
                #判断密码是否正确
                if user.check_password(password):
                    return user #表示用户名(手机号)密码正确,则返回用户对象
        except:
            return None

        return None
